<template>
  <div class="main">
    <el-alert :title="msg" type="error" v-if="isMsg" @close="closeMsg" class="alert-msg"></el-alert>
    <el-dialog title="新增店铺" :visible.sync="showAddStoreDialog" center width="770px">
      <el-form :model="storeData" :rules="rules" ref="storeData">

<!--        <el-form-item label="所属用户id" :label-width="formLabelWidth">-->
<!--          <el-input v-model="storeData.customer_id" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="所属用户" :label-width="formLabelWidth" prop="customer_id">
          <el-select v-model="storeData.customer_id" filterable placeholder="请选择">
            <el-option
              v-for="item in customerList"
              :key="item.customer_id"
              :label="item.nickname"
              :value="item.customer_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="店铺名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="storeData.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="所属省份和城市" :label-width="formLabelWidth">
          <el-cascader placeholder="试试搜索：广东"
                       :options="provinceAndCityList"
                       :props="{ value: 'value', label: 'label'}"
                       @change="handleChange"
                       filterable>
          </el-cascader>
        </el-form-item>


        <el-form-item label="详细地址" :label-width="formLabelWidth">
          <el-input v-model="storeData.address" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="选择联系人" :label-width="formLabelWidth" prop="contact">
          <el-select v-model="storeData.contact" filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in organizationList"
              :key="index"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="联系电话" :label-width="formLabelWidth" prop="telephone">
          <el-input v-model="storeData.telephone" autocomplete="off"></el-input>
        </el-form-item>

        <!--    prop="head_img"     -->
        <el-form-item :label="'联系人二维码'" :label-width="formLabelWidth">
          <div class="upload_head_img">
            <el-upload :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="upload_picture" class="avatar-uploader" action="">
              <img v-if="storeData.wechat_qrcode" :src="storeData.wechat_qrcode" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item :label="'机构图片'" :label-width="formLabelWidth">
          <div class="upload_head_img">
            <el-upload :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="upload_store_img" class="avatar-uploader" action="">
              <img v-if="storeData.store_img" :src="storeData.store_img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="机构介绍" :label-width="formLabelWidth">
          <el-input v-model="storeData.store_introduction" autocomplete="off"></el-input>
        </el-form-item>
        
        <el-form-item :label="'机构logo'" :label-width="formLabelWidth">
          <div class="upload_head_img">
            <el-upload :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="upload_store_logo" class="avatar-uploader" action="">
              <img v-if="storeData.store_logo" :src="storeData.store_logo" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="培训课程" :label-width="formLabelWidth">
          <el-checkbox-group v-model="storeData.subject_id">
            <el-checkbox v-for="subject in subject" :label="subject.id" :key="subject.id">{{subject.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
<!--        不需要添加时间,后台自动生成                                     -->
<!--        <el-form-item label="添加日期" :label-width="formLabelWidth">-->
<!--          <el-input v-model="storeData.date_added" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="最后更新日期" :label-width="formLabelWidth">-->
<!--          <el-input v-model="storeData.date_modified" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit">取 消</el-button>
        <el-button type="primary" @click="submitStore('storeData')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import store from '@/store'
  import {add} from '@/api/thk/store'

  import { client } from '@/utils/alioss'

  import {dateFormat} from '@/utils/dateFormat'
  const subject=['美术','语文','数学','体育']
  export default {
    name: 'addStore',

    data() {
      return {
        subject:[],
        showAddStoreDialog: false,
        formLabelWidth: '130px',
        storeData: {
          customer_id: '',
          name: '',
          province: '',
          city: '',
          address: '',
          country: '',
          contact: '',
          telephone: '',
          wechat_qrcode: '',
          store_img:'',
          store_introduction:'',
          store_logo:'',
          subject_id:[],
          // date_added: '',
          // date_modified: '',
        },
        customerList: [],
        provinceAndCityList: [],
        organizationList: [],
        

        // 这两个字段为当customer对应的store已存在时，不能增加所显示的提示信息
        msg: "",
        isMsg : false,


        // 表单校验规则
        rules: {
          // 店铺名为必须
          name:[
            { required: true, message: '请输入店铺名称', trigger: 'blur' },
          ],
          telephone:[
            { required: true, message: '请输手机号', trigger: 'blur' },
            { min: 11, max: 11, message: '长度必须为11位', trigger: 'blur' }
          ],
          customer_id: [
            { required: true, message: '请选择用户', trigger: 'change' }
          ],

          contact: [
            { required: true, message: '请选择联系人', trigger: 'change' }
          ],

          store_introduction:[
            { required: true, message: '请填写店铺介绍', trigger: 'change'}
          ],

          store_subject:[
            { required: true, message: '请选择课程科目', trigger: 'change'}
          ]
        }
      }
    },



    methods: {
      submitStore(storeData){
        // 设置添加的时间
        this.$refs[storeData].validate((valid) => {
          console.log('store data >>>>>>>')
          console.log(this.storeData)
          if (valid) {
            add(store.getters.token,this.storeData).then(result => {
              // 增加成功
              this.showAddStoreDialog = !this.showAddStoreDialog

              // 一个用户只能有一个店铺，判断创建用户的店铺是否存在(存在则alert一个错误)
              if(result.data.status === false){
                this.msg = result.data.msg
                this.isMsg = true
                setTimeout(()=>{
                  this.isMsg = false
                },3000)
                return
              }else{
                this.$message.success('增加成功!')
              }

              this.$parent.getStoreList()
            }).catch(error => {
              this.$message('增加失败!')
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },

      cancelSubmit(customerList,provinceAndCityList,organizationList,subject){
        this.subject=subject
        this.customerList = customerList
        this.provinceAndCityList = provinceAndCityList
        this.organizationList = organizationList
        this.showAddStoreDialog = !this.showAddStoreDialog
        this.changeCityData()
      },

      // 转换省份数据
      changeCityData(){
        console.log("changeCityList",this.provinceAndCityList)
        let data = {data: this.provinceAndCityList}
        let str = JSON.stringify(data).replace(/province_id/g,'value')
        str = str.replace(/province/g,'label')

        str = str.replace(/city_id/g,'value')
        str = str.replace(/city/g,'label')

        str = str.replace(/country_id/g,'value')
        str = str.replace(/country/g,'label')

        data = JSON.parse(str)
        this.provinceAndCityList = data.data
      },

      handleChange(value){
        if(value){
          this.organizationData.province = value[0]
          this.organizationData.city = value[1]
          this.organizationData.country = value[2]
        }
      },

      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 1
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片只能是 JPG、PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 1MB!')
        }
        return (isJPG | isPNG) && isLt2M
      },
      upload_picture(file) {
        const that = this
        const fileName = 'user-admin_user-picture' + file.file.uid
        client().put(fileName, file.file).then((res) => {
          this.$set(that.storeData, 'wechat_qrcode', res.url)

          // that.storeList.wechat_qrcode = res.url

          console.log(res.url);
          that.$message.success('头像地址上传成功！')
        }).catch((err) => {
          that.$message.error('头像地址上传失败，原因：' + err)
        })
      },
      upload_store_img(file) {
        const that = this
        const fileName = 'user-admin_user-store_img' + file.file.uid
        client().put(fileName, file.file).then((res) => {
          this.$set(that.storeData, 'store_img', res.url)

          // that.storeList.wechat_qrcode = res.url

          console.log(res.url);
          that.$message.success('头像地址上传成功！')
        }).catch((err) => {
          that.$message.error('头像地址上传失败，原因：' + err)
        })
      },
      upload_store_logo(file) {
        const that = this
        const fileName = 'user-admin_user-store_logo' + file.file.uid
        client().put(fileName, file.file).then((res) => {
          this.$set(that.storeData, 'store_logo', res.url)

          // that.storeList.wechat_qrcode = res.url

          console.log(res.url);
          that.$message.success('头像地址上传成功！')
        }).catch((err) => {
          that.$message.error('头像地址上传失败，原因：' + err)
        })
      },
      // 关闭alert的错误信息
      closeMsg(){
        this.isMsg = false
      }


    }
  }
</script>

<style>
  /* 图片上传的样式 */
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    color: #8c939d;
    text-align: center;
  }
  .avatar {
    display: block;
  }

  /* 头像地址(head_img)图片上传组件的尺寸 */
  .upload_head_img .avatar-uploader .el-upload{
  }
  .upload_head_img .avatar-uploader-icon{
    font-size: 28px;
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
  .upload_head_img .avatar{
    width: 80px;
    height: 80px;
  }

  .alert-msg{
    position: absolute;
    height: 30px;
    width: 300px;
    top: 10px;
    left: 500px;
  }

</style>



